﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Idlesoft.Utils;

namespace Idlesoft.ShellAnywhereLanguage
{
	public static class LexemeExtensions
	{
		public static bool IsNullOrEmpty<TItem>(this ILexeme<TItem> lexeme) where TItem : class, IParam
		{
			return lexeme != null || !lexeme.HasItems;
		}
	}

	public class Lexeme<TItem> : ILexeme<TItem>
	where TItem : class, IParam
	{
		#region ctors
		public Lexeme(int dot, params TItem[] items)
		{
			Dot = dot;
			_Items.AddRange(items);
		}
		#endregion ctors

		#region props
		public bool HasItems { get { return _Items.Count > 0; } }
		public TItem Head { get { return _Items.FirstOrDefault(); } }
		public TItem[] Items { get { return _Items.ToArray(); } }
		public bool IsMatched { get { return _Items.Any(item => item.IsMatched(Dot)); } }
		public bool IsUnmatched { get { return _Items.Any(item => item.IsUnmatched(Dot)); } }
		public int Dot { get; internal set; }
		public string Matched { get { return _Items.SingleOrDefault(item => item.IsMatched(Dot)).ToString(); } }
		public string[] Unmatched { get { return _Items.Select(item => item.Unmatched(Dot)).ToArray(); } }
		public TItem MatchedItem { get { return _Items.SingleOrDefault(item => item.IsMatched(Dot)); } }
		public TItem[] UnmatchedItems { get { return _Items.Where(item => item.IsUnmatched(Dot)).ToArray(); } }
		#endregion props

		#region fields
		private List<TItem> _Items = new List<TItem>();
		#endregion fields
	}
}
